<?php

$folders = $db->fetchAll("SELECT * FROM cms_files_folders WHERE site_id=? ORDER BY title", $site['id']);
$smarty->assign('folders', $folders);

$order = $_SESSION['paging'][$path_string]['order'];
$filter = isset($_SESSION['paging'][$path_string]['filter']) ? '%' . $_SESSION['paging'][$path_string]['filter'] . '%' : '%';

if (isset($_REQUEST['id'])) {
	$_SESSION['file_folder_id'] = $_REQUEST['id'];
	$_SESSION['paging'][$path_string]['page'] = 1;
}
if (isset($_SESSION['file_folder_id'])) {
	$folder = $db->fetchRow("SELECT * FROM cms_files_folders WHERE site_id=? AND id=?", array($site['id'], $_SESSION['file_folder_id']));
	
	$files_select = $db->select()
	              ->from(array('f' => 'cms_files'), array('id', 'created', 'modified', 'filename', 'size', 'caption', 'description'))
	              ->order($order)
	              ->where($db->quoteInto('site_id=?', $site['id']))
	              ->where($db->quoteInto('folder_id=?', $_SESSION['file_folder_id']))
	              ->where($db->quoteInto('id LIKE ? OR filename LIKE ?', $filter));
	$files = $db->fetchAll($files_select);
	
	$page   = $_SESSION['paging'][$path_string]['page'];
	$show   = $_SESSION['paging'][$path_string]['show'];
	$offset = ($page - 1) * $show;
	$total  = count($files);
	
	$smarty->assign('order', $order);
	$smarty->assign('page', $page);
	$smarty->assign('show', $show);
	$smarty->assign('filter', $filter);
	$smarty->assign('offset', $offset);
	$smarty->assign('total', $total);
	
	$smarty->assign('files', array_slice($files, $offset, $show));
	
	
	if (isset($_POST['folder'])) {
		
		$folder = array_merge($folder, $_POST['folder']);
		
		$errors = array();
		if (!$folder['title']) $errors[] = 'TITLE';
		
		if (sizeof($errors)) {
			$smarty->assign('errors', $errors);
		} else {
			$smarty->assign('success', true);
			$db->update('cms_files_folders', $folder, array($db->quoteInto("id=?", $_REQUEST['id']), $db->quoteInto("site_id=?", $site['id'])));
		}
	}
	
	
	$smarty->assign('folder', $folder);
	
}

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
	header('Content-type: text/xml');
	$smarty->display('global/files/index.tpl.taconite');
} else {
	$smarty->display('global/files/index.tpl.html');
}
